<?php

namespace App\Models\Sample;

use App\Helpers\Code;
use App\Models\BaseModel;
use App\Models\Basic\DictionaryMember;
use App\Models\Customer\Doctor;
use App\Models\Customer\FamilyMember;
use Illuminate\Support\Facades\Auth;
use DB;

class Sample extends BaseModel
{

    protected $table = 'samples';
    protected $fillable = [
        'family_id', 'family_member_id', 'bar_code', 'note', 'sample_type', 'transport_method', 'deal_method', 'sample_date', 'sampled_by',
        'receive_date', 'received_by', 'salesman', 'organization', 'department', 'doctor', 'state', 'order_state', 'is_normal', 'is_qualified',
        'sample_aim', 'created_by', 'updated_by', 'data_scope',
    ];

    public $sorter = [];
    public $params = ['bar_code'];

    public function createdBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'created_by');
    }

    public function updatedBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'updated_by');
    }

    public function salesman()
    {
        return $this->belongsTo('App\Models\Account\User', 'salesman');
    }

    public function receivedBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'received_by');
    }

    public function family()
    {
        return $this->belongsTo('App\Models\Customer\Family', 'family_id');
    }

    public function familyMember()
    {
        return $this->belongsTo('App\Models\Customer\FamilyMember', 'family_member_id');
    }

    public function type()
    {
        return $this->belongsTo('App\Models\Sample\SampleType', 'sample_type');
    }

    public function transportMethod()
    {
        return $this->belongsTo('App\Models\Basic\DictionaryMember', 'transport_method', 'code');
    }

    public function dealMethod()
    {
        return $this->belongsTo('App\Models\Basic\DictionaryMember', 'deal_method', 'code');
    }

    public function aim()
    {
        return $this->belongsTo('App\Models\Basic\DictionaryMember', 'sample_aim', 'code');
    }

    public function organization()
    {
        return $this->belongsTo('App\Models\Customer\Customer', 'organization');
    }

    public function department()
    {
        return $this->belongsTo('App\Models\Customer\CustomerDepartment', 'department');
    }

    public function doctor()
    {
        return $this->belongsTo('App\Models\Customer\Doctor', 'doctor');
    }

    /*添加样本*/
    public function addSample($data)
    {
        $familyMember = FamilyMember::where(['family_id' => $data['family_id'], 'id' => $data['family_member_id']])->first();
        if (!$familyMember) {
            return Code::INSIDE_ERROR;
        }

        $sampleType = SampleType::find($data['sample_type']);
        if (!$sampleType) {
            return Code::INSIDE_ERROR_1;
        }

        if (isset($data['transport_method']) && !empty($data['transport_method'])) {
            $transportMethod = DictionaryMember::find($data['transport_method']);
            if (!$transportMethod) {
                return Code::INSIDE_ERROR_2;
            }

            $data['transport_method'] = $transportMethod->code;
        }

        if (isset($data['deal_method']) && !empty($data['deal_method'])) {
            $dealMethod = DictionaryMember::find($data['deal_method']);
            if (!$dealMethod) {
                return Code::INSIDE_ERROR_2;
            }

            $data['deal_method'] = $dealMethod->code;
        }

        if (isset($data['sample_aim']) && !empty($data['sample_aim'])) {
            $sampleAim = DictionaryMember::find($data['sample_aim']);
            if (!$sampleAim) {
                return Code::INSIDE_ERROR_2;
            }

            $data['sample_aim'] = $sampleAim->code;
        }

        if (isset($data['received_by']) && !empty($data['received_by'])) {
            $receivedBy = User::find($data['received_by']);
            if (!$receivedBy) {
                return Code::INSIDE_ERROR_3;
            }
        }

        if (isset($data['salesman']) && !empty($data['salesman'])) {
            $salesman = User::find($data['salesman']);
            if (!$salesman) {
                return Code::INSIDE_ERROR_3;
            }
        }

        $doctor = Doctor::where(['id' => $data['doctor'], 'department_id' => $data['department'], 'customer_id' => $data['organization']])->first();
        if (!$doctor) {
            return Code::INSIDE_EXIST_DEPENDENCE;
        }

        $userId = Auth::id();
        $data['created_by'] = $userId;
        $data['updated_by'] = $userId;
        $data['state'] = 0;
        $data['data_scope'] = $this->getDataScope();

        $sampleInoutRecordId = $data['sample_inout_record_id'];
        unset($data['sample_inout_record_id']);
        DB::beginTransaction();
        $model = $this->create($data);
        $sampleInoutRecordDetail = new SampleInoutRecordDetail();
        $sampleInoutRecordDetail->sample_id = $model->id;
        $sampleInoutRecordDetail->sample_inout_record_id = $sampleInoutRecordId;
        $sampleInoutRecordDetail->data_scope = $model->data_scope;
        $sampleInoutRecordDetail->save();
        DB::commit();
        return $model;
    }

    /*删除样本*/
    public function deleteSample($id)
    {
        $model = $this->find($id);
        if (!$model) {
            return null;
        }

        $model->delete();
        SampleInoutRecordDetail::where('sample_id', $id)->delete();
        return true;
    }

    /*编辑样本*/
    public function editSample($data, $id)
    {
        $model = $this->find($id);
        if (!$model) {
            return null;
        }

        $familyMember = FamilyMember::where(['family_id' => $data['family_id'], 'id' => $data['family_member_id']])->first();
        if (!$familyMember) {
            return Code::INSIDE_ERROR;
        }

        $sampleType = SampleType::find($data['sample_type']);
        if (!$sampleType) {
            return Code::INSIDE_ERROR_1;
        }

        if (isset($data['transport_method']) && !empty($data['transport_method'])) {
            $transportMethod = DictionaryMember::find($data['transport_method']);
            if (!$transportMethod) {
                return Code::INSIDE_ERROR_2;
            }

            $data['transport_method'] = $transportMethod->code;
        }

        if (isset($data['deal_method']) && !empty($data['deal_method'])) {
            $dealMethod = DictionaryMember::find($data['deal_method']);
            if (!$dealMethod) {
                return Code::INSIDE_ERROR_2;
            }

            $data['deal_method'] = $dealMethod->code;
        }

        if (isset($data['sample_aim']) && !empty($data['sample_aim'])) {
            $sampleAim = DictionaryMember::find($data['sample_aim']);
            if (!$sampleAim) {
                return Code::INSIDE_ERROR_2;
            }

            $data['sample_aim'] = $sampleAim->code;
        }

        if (isset($data['received_by']) && !empty($data['received_by'])) {
            $receivedBy = User::find($data['received_by']);
            if (!$receivedBy) {
                return Code::INSIDE_ERROR_3;
            }
        }

        if (isset($data['salesman']) && !empty($data['salesman'])) {
            $salesman = User::find($data['salesman']);
            if (!$salesman) {
                return Code::INSIDE_ERROR_3;
            }
        }

        $doctor = Doctor::where(['id' => $data['doctor'], 'department_id' => $data['department'], 'customer_id' => $data['organization']])->first();
        if (!$doctor) {
            return Code::INSIDE_EXIST_DEPENDENCE;
        }

        $data['updated_by'] = $userId = Auth::id();
        return $model->updateOrCreate(['id' => $id], $data);
    }

    /*获取指定样本*/
    public function getSample($id)
    {
        $model = $this->with([
            'createdBy:id,username', 'updatedBy:id,username', 'salesman:id,username', 'receivedBy:id,username', 'type:id,title', 'familyMember:id,title',
            'transportMethod:code,title', 'dealMethod:code,title', 'aim:code,title', 'organization:id,title', 'department:id,title', 'doctor:id,title'
        ])
            ->where('id', $id)
            ->select(['family_id', 'family_member_id', 'bar_code', 'note', 'sample_type', 'transport_method', 'deal_method', 'sample_date', 'sampled_by',
                'receive_date', 'received_by', 'salesman', 'organization', 'department', 'doctor', 'state', 'order_state', 'is_normal', 'is_qualified',
                'sample_aim', 'created_by', 'updated_by'])
            ->first();

        if (!$model) {
            return null;
        }

        return $model;
    }

    /*获取样本列表*/
    public function getSampleList($limit, $sorter, $search, $defaultSorter)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;
        if ($defaultSorter == 'desc') {
            $model = $this->orderBy('created_at', $defaultSorter);
        } else {
            $model = $this->orderBy($sorter[0], $sorter[1]);
        }

        $model->with([
            'createdBy:id,username', 'updatedBy:id,username', 'salesman:id,username', 'receivedBy:id,username', 'type:id,title', 'familyMember:id,title',
            'transportMethod:code,title', 'dealMethod:code,title', 'aim:code,title', 'organization:id,title', 'department:id,title', 'doctor:id,title'
        ])
            ->select(['family_id', 'family_member_id', 'bar_code', 'note', 'sample_type', 'transport_method', 'deal_method', 'sample_date', 'sampled_by',
                'receive_date', 'received_by', 'salesman', 'organization', 'department', 'doctor', 'state', 'order_state', 'is_normal', 'is_qualified',
                'sample_aim', 'created_by', 'updated_by']);

        foreach ($search as $key => $value) {
            switch ($key) {
                case 'bar_code':
                    $model->where($key, 'like', '%' . $value . '%');
                    break;
            }
        }

        return $model->paginate($perPage)->toArray();
    }
}
